using Microsoft.OpenApi.Models;
using WebApi.Filters;

namespace WebApi.Extensions
{
    public static class SwaggerExtensions
    {
        public static void AddSwaggerExt(this IServiceCollection services)
        {
            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            services.AddEndpointsApiExplorer();
            services.AddSwaggerGen(options =>
            {
                #region 配置请求体数据默认值

                options.SchemaFilter<OpenApiDefaultValueSchemaFilter>();

                #endregion 配置请求体数据默认值

                #region 展示代码注释

                string basePath = AppContext.BaseDirectory;
                string xmlPath = Path.Combine(basePath, "WebApi.xml");
                options.IncludeXmlComments(xmlPath);

                #endregion 展示代码注释

                #region Swagger API版本控制

                foreach (string versionName in typeof(ApiVersions).GetEnumNames())
                {
                    options.SwaggerDoc(versionName, new Microsoft.OpenApi.Models.OpenApiInfo()
                    {
                        Title = $"这里是 {versionName} 版本的API",
                        Version = versionName,
                        Description = $"Core API {versionName} 版本"
                    });
                }

                #endregion Swagger API版本控制

                #region Token 传值

                options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                {
                    Type = SecuritySchemeType.ApiKey,
                    In = ParameterLocation.Header,
                    Name = "Authorization",
                    Description = "请输入token，格式为 Bearer XXXXXXXXXX",
                    Scheme = "Bearer",
                    BearerFormat = "JWT"
                });

                options.AddSecurityRequirement(new OpenApiSecurityRequirement()
                {
                    {
                        new OpenApiSecurityScheme()
                        {
                            Reference = new OpenApiReference()
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id = "Bearer"
                            }
                        }, new List<string>()
                    }
                });

                #endregion Token 传值
            });
        }

        public static void UseSwaggerExt(this WebApplication app)
        {
            app.UseSwagger();
            app.UseSwaggerUI(options =>
            {
                #region Swagger API 版本控制

                foreach (string versionName in typeof(ApiVersions).GetEnumNames())
                {
                    options.SwaggerEndpoint($"/swagger/{versionName}/swagger.json", versionName);
                }

                #endregion Swagger API 版本控制
            });
        }
    }
}